package leetcode;

public class CountAndSay38 {

	public static void main(String[] args) {
		System.out.println("Result: " + countAndSay(4));
	}

	public static String countAndSay(int n) {
		if(n == 1) {
			return "1";
		}
		return decodeFromPrevious(countAndSay(n - 1));
	}
	
	public static String decodeFromPrevious(String s){
		StringBuilder sBuilder = new StringBuilder();
		
		char prev = s.charAt(0);
		int count = 1;
		for(int i = 1; i < s.length(); i++) {
			if(s.charAt(i) == prev) {
				count++;
			}else {
				sBuilder.append(count);
				sBuilder.append(prev);
				prev = s.charAt(i);
				count = 1;
			}
		}
		
		sBuilder.append(count);
		sBuilder.append(prev);
		
		return sBuilder.toString();
	}

}
